﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraBars.Ribbon;
using CNotebook;
using CNotebook.Purchases;

namespace NotebookS2
{
    public partial class APVoucherDocument : RibbonForm
    {
        public APVoucherDocument()
        {
            InitializeComponent();
        }

        public const int ObjectType = 19;
        public string ActiveUserId { get; set; }
        public string ConnectionString { get; set; }
        public DataTable LineItems { get; set; }

        #region Function/Methods

        public void PrintPreview()
        {
            PRNT_AP_VOUCHER oPrint = new PRNT_AP_VOUCHER();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocNum.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }
        public void CopyFromToVoucher(APVoucherUnit oUnit)
        {
            dtDateCreated.EditValue = System.DateTime.Now;
            txtCreatedBy.Text = this.ActiveUserId;
            dtDateModified.EditValue = System.DateTime.Now;
            txtModifiedBy.Text = this.ActiveUserId;
            txtStatus.Text = "Draft";

            txtDocNum.Text = oUnit.DocumentNumber;
            dtPostingDate.EditValue = oUnit.PostingDate;

            txtCardCode.Text = oUnit.CardCode;
            txtCardName.Text = oUnit.CardName;
            txtReference.Text = oUnit.Reference;
            txtRemarks.Text = oUnit.Remarks;
            txtTotalAmount.Text = oUnit.TotalAmount.ToString("#,###.00");

            this.LineItems = oUnit.LineItems;

            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();
        }

        public void ShowSearch()
        {
            FND_AP_VOUCHER oForm = new FND_AP_VOUCHER();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            if (oForm.SelectedDocumentNumber != "")
            {
                APVoucherManager oManager = new APVoucherManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                DataTable dt = oManager.GetAPVoucher(oForm.SelectedDocumentNumber);
                DataTable dtLineItems = oManager.GetAPVLineItems(oForm.SelectedDocumentNumber);

                oManager.Close();


                DataRow oRow = dt.Rows[0];

                txtDocNum.Text = oRow["DocNum"].ToString();
                dtPostingDate.EditValue = (DateTime)oRow["PostingDate"];
                
                txtCardCode.Text = oRow["CardCode"].ToString();
                txtCardName.Text = oRow["CardName"].ToString();
                txtRemarks.Text = oRow["Remarks"].ToString();
                txtReference.Text = oRow["Reference"].ToString();

                txtStatus.Text = oRow["DocStatus"].ToString();
                dtDateCreated.EditValue = (DateTime)oRow["DateCreated"];
                txtCreatedBy.Text = oRow["CreatedBy"].ToString();
                dtDateModified.EditValue = (DateTime)oRow["DateModified"];
                txtModifiedBy.Text = oRow["ModifiedBy"].ToString();

                gridControl1.DataSource = dtLineItems;
                gridControl1.Refresh();

                double _totalAmount = Convert.ToDouble(oRow["TotalAmount"]);
                txtTotalAmount.Text = _totalAmount.ToString("#,###.00");
                btnAdd.Text = "Update";
                

            }

        }

        void DisableControls()
        {
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            txtRemarks.Enabled = false;

            txtDocNum.Enabled = false;
            dtPostingDate.Enabled = false;

            btnAdd.Enabled = false;

            gridView1.OptionsBehavior.Editable = false;



        }

        void EnableControls()
        {
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtRemarks.Enabled = true;

            txtDocNum.Enabled = true;
            dtPostingDate.Enabled = true;

            btnAdd.Enabled = true;

            gridView1.OptionsBehavior.Editable = true;

        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = ObjectType.ToString();

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocNum.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void InitializeSeries()
        {

            string _ObjectType = ObjectType.ToString();
            
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();


            if (oSeries.IsAutoNumber(_ObjectType) == true)
            {
                txtDocNum.Properties.ReadOnly = true;
                txtDocNum.Text = "##########";

            }
            oSeries.Close();



        }

        void InitializeLineItems()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("DocType", typeof(string));
            dt.Columns.Add("DocNum", typeof(string));
            dt.Columns.Add("RefDocument", typeof(string));
            dt.Columns.Add("RefInvoice", typeof(string));
            dt.Columns.Add("RefDocDate", typeof(DateTime));
            dt.Columns.Add("CardCode", typeof(string));
            dt.Columns.Add("CardName", typeof(string));
            dt.Columns.Add("Amount", typeof(double));
            

            this.LineItems = dt;
        }

        void RemoveBlankLastRowFirst()
        {
            
            gridView1.MoveLast();
            try
            {
                int iCount = gridView1.FocusedRowHandle;
                string sItemCode = "";


                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["RefDocument"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView1.DeleteRow(iCount);
                }
            }
            catch { }

        }

        void ComputeTotal()
        {
            double _total = 0;
            foreach (DataRow oRow in this.LineItems.Rows)
            {
                try
                {
                    _total = _total + Convert.ToDouble(oRow["Amount"]);
                }
                catch
                {
                }
            }

            txtTotalAmount.Text = _total.ToString("#,###.00");
        }

        #endregion

        #region Events
        private void APCounterDocument_Load(object sender, EventArgs e)
        {
            InitializeSeries();

            txtCreatedBy.Text = this.ActiveUserId;
            txtModifiedBy.Text = this.ActiveUserId;

            dtPostingDate.EditValue = System.DateTime.Now;
            dtDateCreated.EditValue = System.DateTime.Now;
            dtDateModified.EditValue = System.DateTime.Now;

            if (this.LineItems == null)
            {
                InitializeLineItems();

                gridControl1.DataSource = this.LineItems;
                gridControl1.Refresh();

                if (gridView1.RowCount == 0)
                {
                    gridView1.AddNewRow();
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtCardCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            
            try
            {
                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Vendor";
                _SearchBP.ShowDialog();

                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
 
                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void txtCardCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByBPCode(txtCardCode.Text, "Vendor");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.BusinessPartnerType = "Vendor";
                            _SearchBP.SetSearchByBPCode(txtCardCode.Text);

                            _SearchBP.ShowDialog();

                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            
                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    
                }
                catch
                {
                }
            }
        }

        private void txtReceiptNum_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            string sDocType = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["DocType"]).ToString();

            if (sDocType == "Receiving Report")
            {

                FND_GRPO_COUNTER oForm = new FND_GRPO_COUNTER();

                oForm.ConnectionString = this.ConnectionString;
                oForm.VendorCode = txtCardCode.Text;
                oForm.ShowDialog();

                int iRowHandle = gridView1.FocusedRowHandle;

                gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["RefDocument"], oForm.DocumentNumber);
                gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["RefInvoice"], oForm.RefInvoiceNumber);
                gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["RefDocDate"], oForm.DocumentDate);
                gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["CardCode"], oForm.VendorCode);
                gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["CardName"], oForm.VendorName);
                gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["Amount"], oForm.NetAmount);
                
            }
            else
            {
                FND_RCPT_SVC_COUNTER oSearchDocument = new FND_RCPT_SVC_COUNTER();

                oSearchDocument.ConnectionString = this.ConnectionString;
                oSearchDocument.CardCode = txtCardCode.Text;
                oSearchDocument.ShowDialog();

                string sDocumentNumber = oSearchDocument.DocumentNumber;


                if (sDocumentNumber != null )
                {

                    if (sDocumentNumber.Trim() != "")
                    {
                        ServiceReceiptManager oManager = new ServiceReceiptManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        DataRow oRow = oManager.GetPurchaseOrder(sDocumentNumber);

                        #region Loading to grid
                        int iRowHandle = gridView1.FocusedRowHandle;

                        gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["RefDocument"], oRow["DocNum"].ToString());
                        gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["RefInvoice"], oRow["InvDRNo"].ToString());
                        gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["RefDocDate"], oRow["PostingDate"]);
                        gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["CardCode"], oRow["CardCode"].ToString());
                        gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["CardName"], oRow["CardName"].ToString());
                        gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["Amount"], oRow["NetAmount"].ToString());
                        
                        #endregion

                        oManager.Close();

                        btnAdd.Text = "Update";

                        ComputeTotal();
                    }
                }

            }

        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (gridView1.IsLastRow)
                {
                    string _REFERENCE_RECEIVING = "";
                    int iCount = gridView1.FocusedRowHandle;

                    _REFERENCE_RECEIVING = gridView1.GetRowCellValue(iCount, gridView1.Columns["RefDocument"]).ToString();

                    if (_REFERENCE_RECEIVING != "")
                    {
                        gridView1.AddNewRow();

                        gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        gridView1.FocusedColumn = gridView1.VisibleColumns[0];
                        gridView1.ShowEditor();
                    }
                }
            }
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            RemoveBlankLastRowFirst();
            if (btnAdd.Text == "Add")
            {
                APVoucherManager oManager = new APVoucherManager();
                APVoucherUnit oUnit = new APVoucherUnit();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                txtDocNum.Text = GetNewSeries();
                oUnit.DocumentNumber = txtDocNum.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.PostingDate = (DateTime)dtPostingDate.EditValue;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.TotalAmount = Convert.ToDouble(txtTotalAmount.Text.Replace(",", ""));
                oUnit.Reference = txtReference.Text;

                oUnit.DocStatus = txtStatus.Text;
                oUnit.DateCreated = System.DateTime.Now;
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = System.DateTime.Now;
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.LineItems = this.LineItems;

                oManager.AddVoucher(oUnit);

                oManager.Close();

                btnAdd.Text = "Update";

                MessageBox.Show("Document successfully added!!!", "Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                APVoucherManager oManager = new APVoucherManager();
                APVoucherUnit oUnit = new APVoucherUnit();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                txtDocNum.Text = GetNewSeries();
                oUnit.DocumentNumber = txtDocNum.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.PostingDate = (DateTime)dtPostingDate.EditValue;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.TotalAmount = Convert.ToDouble(txtTotalAmount.Text.Replace(",", ""));
                oUnit.Reference = txtReference.Text;

                oUnit.DocStatus = txtStatus.Text;
                oUnit.DateCreated = System.DateTime.Now;
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = System.DateTime.Now;
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.LineItems = this.LineItems;

                oManager.UpdateVoucher(oUnit);

                oManager.Close();

                MessageBox.Show("Document successfully updated!!!", "Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            if (txtStatus.Text != "##########")
            {
                if (txtStatus.Text == "Draft")
                {

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        //DeliverOrder(txtDocumentNumber.Text);

                        if (MessageBox.Show("Are you sure you want to post this Document?", "Post Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        {
                            APVoucherManager oManager = new APVoucherManager();

                            oManager.ConnectionString = this.ConnectionString;
                            oManager.Open();

                            oManager.PostDocument(txtDocNum.Text);

                            oManager.Close();

                            txtStatus.Text = "Posted";

                            #region closing references

                            if (txtReference.Text != "")
                            {
                                APCounterManager oAPCounterManager = new APCounterManager();
                                oAPCounterManager.ConnectionString = this.ConnectionString;
                                oAPCounterManager.Open();

                                oAPCounterManager.CloseDocument(txtReference.Text);

                                oAPCounterManager.Close();
                                
                            }
                            else
                            {
                                foreach (DataRow oRow in this.LineItems.Rows)
                                {
                                    if (oRow["DocType"].ToString() == "Receiving Report")
                                    {
                                        GoodsReceivingReportManager oWRR = new GoodsReceivingReportManager();

                                        oWRR.ConnectionString = this.ConnectionString;
                                        oWRR.Open();

                                        oWRR.SetAppliedAmount(oRow["RefDocument"].ToString(), oRow["Amount"].ToString());
                                        oWRR.Close();
                                    }
                                    else
                                    {
                                        ServiceReceiptManager oSrvRcpt = new ServiceReceiptManager();
                                        oSrvRcpt.ConnectionString = this.ConnectionString;
                                        oSrvRcpt.Open();

                                        oSrvRcpt.SetAppliedAmount(oRow["RefDocument"].ToString(), oRow["Amount"].ToString());
                                        oSrvRcpt.Close();
                                    }
                                }
                            }
                            #endregion

                            MessageBox.Show("Document is already posted", "Post Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {

                        if (MessageBox.Show("Are you sure you want to cancel this Document?", "Cancel Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        {
                            APVoucherManager oManager = new APVoucherManager();

                            oManager.ConnectionString = this.ConnectionString;
                            oManager.Open();

                            oManager.CancelDocument(txtDocNum.Text);

                            oManager.Close();

                            txtStatus.Text = "Canceled";
                            MessageBox.Show("Document is already Canceled", "Cancel Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else
                {

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        if (MessageBox.Show("Are you sure you want to close this Document?", "Close Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        {

                            APVoucherManager oManager = new APVoucherManager();

                            oManager.ConnectionString = this.ConnectionString;
                            oManager.Open();

                            oManager.CloseDocument(txtDocNum.Text);

                            oManager.Close();

                            txtStatus.Text = "Closed";
                            MessageBox.Show("Document is already closed", "Close Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();

            }

          
            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
            }
        }

        #endregion

        private void txtReference_EditValueChanged(object sender, EventArgs e)
        {
            if (txtReference.Text != "")
            {
                txtManual.Visible = false;
            }
            else
            {
                txtManual.Visible = true;
            }
        }

        
    }
}